package com.example.exchangeapp.zjs;

import static android.content.ContentValues.TAG;

import static com.example.exchangeapp.yy.constant.AppId.AppId;
import static com.example.exchangeapp.yy.constant.AppSecret.appSecret;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.exchangeapp.R;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ProductDetailActivity extends AppCompatActivity {
    private Product product;
    private final Gson gson = new Gson();

    //请求人信息和消费金额
    private int buyerId;
    private Double productPrice;
    private Double oldPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);

        // 接收"商品项的点击事件"传递过来的商品信息
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("product")) {
            product = intent.getParcelableExtra("product");

            // 根据商品信息找到对应的视图组件，例如：
            ImageView imageView = findViewById(R.id.imageView_product);
            // 使用图片加载库（如Glide、Picasso）加载商品图片
            if (product.getImageUrlList() == null || product.getImageUrlList().size()==0) {
                Glide.with(this).load(R.drawable.default_product_image).into(imageView);
            }else {
                Glide.with(this).load(product.getImageUrlList().get(0)).into(imageView);
            }

            TextView priceTextView = findViewById(R.id.textView_price);
            priceTextView.setText(String.valueOf("商品价格："+product.getPrice()));

            TextView contentTextView = findViewById(R.id.textView_content);
            contentTextView.setText("商品描述："+product.getContent());

            TextView typeNameTextView = findViewById(R.id.textView_type_name);
            typeNameTextView.setText("商品分类："+product.getTypeName());

            TextView usernameTextView = findViewById(R.id.textView_username);
            usernameTextView.setText("卖家名："+product.getUsername());

            TextView addrTextView = findViewById(R.id.textView_addr);
            addrTextView.setText("卖家地址："+product.getAddr());

            Button buttonBuy = findViewById(R.id.button_buy);
            buttonBuy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showBuyConfirmationDialog();
                }
            });
        }
    }

    //购买商品点击事件
    private void showBuyConfirmationDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("购买商品")
                .setMessage("是否购买此商品？")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        postBuyProduct();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showPurchaseCancelledMessage();
                    }
                });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    //发送购买商品请求
    public void postBuyProduct(){
        new Thread(() -> {

            //请求人信息
            GetUserStatus getUserStatus=new GetUserStatus(this);
            Cursor cursor=getUserStatus.getDataFromDatabase();
            while(cursor.moveToNext()){
                int index0=cursor.getColumnIndex("ID");
                int index1=cursor.getColumnIndex("money");
                buyerId=cursor.getInt(index0);
                oldPrice=cursor.getDouble(index1);
            }
            int goodsId=product.getId();
            productPrice=product.getPrice();
            int sellerId= Integer.parseInt(product.getUserId());

            // 请求的url路径
            String url = "http://47.107.52.7:88/member/tran/trading";

            //我的f9ed7014c8cb45169ab4cc0728775790和26073a2f31b8baca64eca93c3c2c5a3dd2313
            //yy的ea0f4556cf414613a551ca2c25840189和139172f805f8d3e654ffb891d963d96f64f62
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", AppId)
                    .add("appSecret", appSecret)
                    .add("Content-Type", "application/json")
                    .build();

            // 请求体
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("buyerId", buyerId);
            bodyMap.put("goodsId", goodsId);
            bodyMap.put("price", productPrice);
            bodyMap.put("sellerId", sellerId);
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callbackBuyProduct);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    public final Callback callbackBuyProduct = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "连接服务器失败!");
            e.printStackTrace();
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("json串为", "购买结果为："+body);
            ProductResponse dataResponseBody = gson.fromJson(body, ProductResponse.class);
            Log.d("个人信息为", dataResponseBody.toString());
            if (dataResponseBody.getCode() == 200) {
                //获取可写数据库
                MySQLiteOpenHelper mySQLiteHelper = new MySQLiteOpenHelper(ProductDetailActivity.this);
                SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();

                //更新数据库金额
                Double newPrice=oldPrice-productPrice;
                //ContentValues 封装数据
                ContentValues values = new ContentValues();
                values.put("money", newPrice);
                //条件语句
                String selection = "ID="+buyerId;
                //条件参数，与条件语句中的一一对应
                //String[] selectionArgs = { "MyOldTitle" };

                //执行更新语句
                int count = db.update(
                        "Users",
                        values,
                        selection,
                        null);

                //成功显示信息
                showPurchaseSuccessMessage();

            }else {
                showPurchaseFailedMessage();
            }
        }
    };

    //使用runOnUiThread()方法在主线程上运行
    private void showPurchaseSuccessMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ProductDetailActivity.this, "购买成功！", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showPurchaseFailedMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ProductDetailActivity.this, "购买失败！", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showPurchaseCancelledMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ProductDetailActivity.this, "已取消购买！", Toast.LENGTH_SHORT).show();
            }
        });
    }

}